package cn.bdqn.mallmgr.controller.rec;

import cn.bdqn.mallmgr.pojo.User;
import cn.bdqn.mallmgr.service.UserService;
import cn.bdqn.mallmgr.tools.RedisTool;
import cn.bdqn.mallmgr.tools.TokenTool;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author
 * @create 2022-07-12 11:36
 */
@Controller
public class LoginController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTool redisTool;

    /**
     * 登录
     *
     * @param userName 用户名
     * @param password 密码
     * @return java.lang.String
     */
    @PostMapping("login")
    @ResponseBody
    public String login(@RequestParam String userName, @RequestParam String password) {
        HashMap<String, Object> result = new HashMap<>();
        User user = userService.login(userName, password);
        if (user == null) {
            result.put("code", 401);
            result.put("error", "登录失败");
        } else {
            String token = TokenTool.createToken(user);
            redisTool.set(token, JSONObject.toJSONString(user), 3000);
            result.put("token", token);
            result.put("code", 200);
            result.put("nickName", user.getUserNickName());
        }
        return JSONArray.toJSONString(result);
    }
}
